package com.comtom.soft.thrift.common;

import java.lang.reflect.Constructor;

import org.apache.thrift.TProcessor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author nobody
 * 服务注册工具，根据bean是否符合规范，注册服务
 */
public class RegisterUtil {
	
    private final static Logger logger = LoggerFactory.getLogger(RegisterUtil.class);
    
	private RegisterUtil(){
		super();
	}
		
	/**
	 * 获取IfceClass的类
	 * @param bean
	 * @return
	 */
	public static Class<?> getIfaceClass(Object bean){
		Class<?> serviceClass = bean.getClass();
		// 获取实现类接口
		Class<?>[] interfaces = serviceClass.getInterfaces();
		if (interfaces.length == 0) {
			return null;
		}
		for (Class<?> clazz : interfaces) {
			String cname = clazz.getSimpleName();
			if (!cname.equals("Iface")) {
				continue;
			}
			return clazz;
		}
		return null;
	}
	
	/**
	 * 根据bean反射构造TProcessor
	 * @param ifaceClass
	 * @param bean
	 * @return
	 */
	public static TProcessor constructorProssor(Class<?> ifaceClass,Object bean){
		String ProcessorClass=getProcessorName(ifaceClass);
		ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
		try {
			Class<?> pclass = classLoader.loadClass(ProcessorClass);
			if (!TProcessor.class.isAssignableFrom(pclass)) {
				return null;
			}
			Constructor<?> constructor = pclass.getConstructor(ifaceClass);
			TProcessor tprocessor = (TProcessor) constructor.newInstance(bean);
			return tprocessor;
		} catch (Exception e) {
			logger.error("构造TProcessor失败:"+e.getLocalizedMessage());
			return null;
		}

	}
	

	/**
	 * 根据IFace获取Processor的全类名
	 * @param ifaceClass
	 * @return
	 */
	private static String getProcessorName(Class<?> ifaceClass){
		return ifaceClass.getEnclosingClass().getName()+"$Processor";
	}
	
}
